/**
 * Copyright (C) 2021 - 2031 O-Cubes Co., Ltd.
 */

/****************************************************************
 *  @file    uart_test.c
 *  @brief   UART testcase source file
 *  @version v1.0
 *  @date    03. Apr. 2023
 ****************************************************************/

#include <string.h>

#include "printf.h"
#include "hal_api.h"
#include "device_uart.h"

typedef void (*Uart_IntCallback) (void *ptr);

static int32_t uart_control(uint32_t uart_id, uint32_t ctrl_cmd, void *param)
{
	DEV_UART_PTR dev_uart_ptr = uart_get_dev(uart_id);
	if (dev_uart_ptr == NULL)
		return RET_FAILED;

	return dev_uart_ptr->uart_control(ctrl_cmd, param);
}

static int32_t uart_set_tx_int(uint32_t uart_id, uint32_t int_en)
{
	return uart_control(uart_id, UART_CMD_SET_TXINT, CONV2VOID(int_en));
}

static int32_t uart_set_tx_cb(uint32_t uart_id, Uart_IntCallback tx_cb)
{
	return uart_control(uart_id, UART_CMD_SET_TXCB, CONV2VOID(tx_cb));
}

static void uartx_irq_callback(void *ptr)
{
	CALLBACK_INFO *cb_info = (CALLBACK_INFO *)ptr;
	uint32_t uart_id = *((uint32_t *)cb_info->param);
	uint32_t int_en = 0;
	char desc[64] = { 0 };

	if (cb_info->cb_type == INT_CALLBACK_TX)
	{
		snprintf(desc, sizeof(desc), "UART%lu interrupt handler\r\n", uart_id);
		Hal_Uart_PutStr(uart_id, desc, strlen(desc));
		uart_set_tx_int(uart_id, int_en);
		uart_set_tx_cb(uart_id, NULL);
	}
}

int32_t test_uartx(void)
{
	char desc[64] = { 0 };
	uint32_t uart_id = 0;
	uint32_t int_en = 1;

	printf("\r\n[UART]: TEST START\r\n");

	/* Polling mode test */
	for (uart_id = DW_UART_0_ID; uart_id < DW_UART_NUM; uart_id++)
	{
		printf("[UART%lu]: Polling Mode OUTPUT TEST\r\n", uart_id);
		snprintf(desc, sizeof(desc), "Polling Mode, UART%lu, hello, world!\r\n", uart_id);
		Hal_Uart_PutStr(uart_id, desc, strlen(desc));
		Hal_Cnt_DelayMs(500);
	}

	/* Interrupt mode test */
	for (uart_id = DW_UART_0_ID; uart_id < DW_UART_NUM; uart_id++)
	{
		printf("[UART%lu]: Interrupt Mode OUTPUT TEST\r\n", uart_id);
		uart_set_tx_cb(uart_id, uartx_irq_callback);
		uart_set_tx_int(uart_id, int_en);
		Hal_Cnt_DelayMs(500);
	}

	printf("[UART]: TEST END\r\n");

	return 0;
}

